package com.situ.mall.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.mall.common.ServerResponse;
import com.situ.mall.entity.Product;
import com.situ.mall.mapper.ProductMapper;
import com.situ.mall.service.IProductService;
@Service
public class ProductServiceImpl implements IProductService {
	@Autowired
	private ProductMapper productMapper;
	
	@Override
	public List<Product> list() {
		return productMapper.list();
	}

	@Override
	public ServerResponse pageList(Integer page, Integer limit,Product product) {
		//设置分页插件
		PageHelper.startPage(page,limit);
		//执行查询
		List<Product> list = productMapper.pageList(product);
		//使用pageInfo对结果包装
		PageInfo pageInfo = new PageInfo(list);
		Integer count = (int)pageInfo.getTotal();
		return ServerResponse.createSuccess("查询成功", count, list);
	}
	//根据id删除
	@Override
	public ServerResponse deleteById(Integer id) {
		try {
			Integer count = productMapper.deleteByPrimaryKey(id);
			if (count == 1) {
				return ServerResponse.createSuccess("删除成功");
			} else {
				return ServerResponse.createError("删除失败");
			}
		} catch (Exception e) {
			return ServerResponse.createError("删除失败");
		}
	}
	//批量删除
	@Override
	public ServerResponse deleteAll(String ids) {
		String[] idArray = ids.split(","); //把字符串分为字符数组
		try {
			Integer count = productMapper.deleteAll(idArray);
			if (count == idArray.length) {
				return ServerResponse.createSuccess("删除成功");
			} else {
				return ServerResponse.createError("删除失败");
			}
			
		} catch (Exception e) {
			return ServerResponse.createError("删除失败");
		}
	}
	
	//添加
	@Override
	public ServerResponse insert(Product product) {
		try {
			Integer count = productMapper.insert(product);
			if (count == 1) {
				return ServerResponse.createSuccess("添加成功");
			} else {
				return ServerResponse.createError("添加失败");
			}
		} catch (Exception e) {
			return ServerResponse.createError("添加失败");
		}
	}

	@Override
	public Product toUpDate(Integer id) {
		return productMapper.selectByPrimaryKey(id);
	}

	@Override
	public ServerResponse update(Product product) {
		try {
			Integer count = productMapper.updateByPrimaryKeySelective(product);
			if (count == 1) {
				return ServerResponse.createSuccess("修改成功");
			} else {
				return ServerResponse.createSuccess("修改失败");
			}
		} catch (Exception e) {
			return ServerResponse.createSuccess("修改失败");
		}
	}

	//前台商品分类展示
	@Override
	public List<Product> selectProduct(Integer categoryId) {
		return productMapper.selectProduct(categoryId);
	}

	@Override
	public Product selectProductDetail(Integer id) {
		return productMapper.selectByPrimaryKey(id);
	}

	@Override
	public Product selectByPrimaryKey(Integer productId) {
		return productMapper.selectByPrimaryKey(productId);
	}

}
